package si.yun.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.*;
import org.springframework.stereotype.Service;
import si.yun.dao.SyUserMapper;
import si.yun.utils.Md5Utils;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @ClassName: spring安全框架的登录权限
 * @Description: TODO
 * @Author: 李振海
 * @Date 2021/9/30 9:14
 */
@Service
public class UserDetailController implements UserDetailsService {

    @Autowired
    private PasswordEncoder PasswordEncoder;

    @Autowired
    private SyUserMapper syUserMapper;

    @Autowired
    private HttpSession session;



    /*
    * 登录
    * */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //去数据库获取该用户的数据
        Map<String, Object> userName = syUserMapper.getUserName(s);

        //1.根据用户名去数据库查询，如果不存在抛出异常（UsernameNotFoundException）
        if(userName==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //创建一个集合用来存储该用户相对应得权限
        Set<String> list=new HashSet<>();

        //获取该用户相对用的角色权限
        Set<String> getRole=syUserMapper.getUserAuthority(s);
        //获取后台部门相对应的权限
        Set<String> deptAuthority = syUserMapper.getDeptAuthority(s);
        Set<String> roleAuthority = syUserMapper.getRoleAuthority(s);
        list.addAll(getRole);
        list.addAll(deptAuthority);
        list.addAll(roleAuthority);

        String s1 = String.valueOf(list);

        String strip = StringUtils.strip(s1, "[]");
        session.setAttribute("user",userName);

        //commaSeparatedStringToAuthorityList权限多个使用逗号分割，会转为list
        /*
        *角色必须由ROLE_开头
        * commaSeparatedStringToAuthorityList内定义权限
        * 将用户拥有的权限返回，
        * */
        return new User(s, (String) userName.get("password"), AuthorityUtils
        .commaSeparatedStringToAuthorityList(strip));
    }
}
